/**
 * Created by LeungZ on 2016/8/10.
 */

import alertTmp from '../form/alert.html';
import alertCtrl from '../form/alert.ctrl.js';
import advTmp from './form/advance.html';
import advCtrl from './form/advance.ctrl.js';
import logTmp from './form/log.html';
import logCtrl from './form/log.ctrl.js';
import rollTmp from './form/rollback.html';
import rollCtrl from './form/rollback.ctrl.js';
import repCtrl from './form/replicas.ctrl.js';
import repTmp from './form/replicas.html';

class Detail {
    constructor(detail, $stateParams, appSrv, ctgNotification, services, ctgColor, $uiModal, $scope, $timeout, serviceSrv) {
        "ngInject";
        this._notification = ctgNotification;
        this._uiModal = $uiModal;
        this._appSrv = appSrv;
        this._serviceSrv = serviceSrv;
        this._color = ctgColor;
        this._timeout = $timeout;
        this.id = $stateParams.id;
        this.timer = {};
        this.edition = false;

        if (detail) {
            this.appCode = detail.appCode;
            this.appName = detail.appName;
            this.content = detail.description;
            this.k8sCode = detail.k8sCode;
            this.namespace=detail.namespace;
        }

        this.page = {
            currentPage: 1,
            totalItems: 0
        };

        if (services) {
            this.serviceList = services.list;
            angular.forEach(services.list, ser=> {
                ser.border = {'border-left': '2px groove ' + this._color[ser.serviceId % this._color.length]};
                ser.color = {'color': this._color[ser.serviceId % this._color.length]};
                this.checkState(ser);
            });
            this.page.totalItems = services.total;
        } else this.serviceList = [];

        $scope.$on('$destroy', ()=> {
            angular.forEach(Object.keys(this.timer), timeId=> {
                this._timeout.cancel(this.timer[timeId]);
            })
        })
    }

    getList() {
        this.serviceList = null;
        this._appSrv.getServiceOfApp({id: this.id, currentPage: this.page.currentPage}).then(data=> {
            this.serviceList = data.list;
            this.page.totalItems = data.total;
            angular.forEach(this.serviceList, ser=> {
                ser.border = {'border-left': '2px groove ' + this._color[ser.serviceId % this._color.length]};
                ser.color = {'color': this._color[ser.serviceId % this._color.length]};
                this.checkState(ser);
            });
        }).catch(data=> {
            this.serviceList = [];
            this._notification.error('获取应用服务列表数据有误.');
        });
    }

    checkState(elem) {
        this._serviceSrv.getDPDetail({
            name: elem.dpName,
            namesp: elem.namespace,
            code: elem.k8sCode
        }).then(data=> {
            elem.newRs = data.newReplicaSet;
            elem.oldTable = data.oldReplicaSetList.replicaSets;
        });

        if (elem.releaseState == '001') {
            this._appSrv.getServiceDetail(elem.serviceId).then(data=> {
                angular.extend(elem, data);
                if (elem.releaseState == '001') {
                    this.timer[elem.serviceId] = this._timeout(this.checkState(elem), 5000);
                }
            });
        }
    }

    deleteService(elem) {
        this._uiModal.open({
            templateUrl: alertTmp,
            controller: alertCtrl,
            controllerAs: 'vm',
            windowClass: 'alert-dialog alert-dialog-ctg',
            resolve: {
                alert: function () {
                    return {
                        appCode: elem.dpName,
                        action: '移除'
                    }
                }
            }
        }).result.then(()=> {
                elem.loading = true;
                this._appSrv.deleteService(elem.serviceId).then(data=> {
                    this._notification.success('移除服务成功.');
                    if (this.serviceList.length == 1 && this.page.currentPage > 1)  this.page.currentPage--;
                    this.getList();
                }).catch(data=> {
                    this._notification.error('移除服务失败. ' + data.resultMsg);
                }).finally(()=> {
                    elem.loading = false;
                })
            });
    }

    stopService(elem) {
        this._uiModal.open({
            templateUrl: alertTmp,
            controller: alertCtrl,
            controllerAs: 'vm',
            windowClass: 'alert-dialog alert-dialog-ctg',
            resolve: {
                alert: function () {
                    return {
                        appCode: elem.dpName,
                        action: '停用'
                    }
                }
            }
        }).result.then(()=> {
                elem.loading = true;
                this._appSrv.stopService(elem.serviceId).then(data=> {
                    this._notification.success('停用服务版本成功.');
                    elem.state = '002';
                    this.checkState(elem);
                }).catch(data=> {
                    elem.state = '001';
                    this._notification.error('停用服务版本失败. ' + data.resultMsg);
                }).finally(()=> {
                    elem.loading = false;
                })
            });
    }

    startService(elem) {
        elem.loading = true;
        this._appSrv.startService(elem.serviceId).then(data=> {
            this._notification.success('启用服务版本成功.');
            elem.state = '001';
            this.checkState(elem);
        }).catch(data=> {
            elem.state = '002';
            this._notification.error('启用服务版本失败. ' + data.resultMsg);
        }).finally(()=> {
            elem.loading = false;
        })
    }

    openAdvanceForm(ser) {
        this._uiModal.open({
            templateUrl: advTmp,
            controller: advCtrl,
            backdrop: 'static',
            controllerAs: 'service',
            size: 'lg',
            resolve: {
                service: function () {
                    return ser;
                }
            }
        })
    }


    openLogForm(elem) {
        this._uiModal.open({
            animation: true,
            templateUrl: logTmp,
            controller: logCtrl,
            controllerAs: 'vm',
            size: 'lg',
            resolve: {
                yaml: function () {
                    return elem.yamlContent
                }
            }
        });
    }

    openRollForm(elem) {
        this._uiModal.open({
            animation: true,
            templateUrl: rollTmp,
            controller: rollCtrl,
            controllerAs: 'vm',
            size: 'md',
            resolve: {
                service: function () {
                    return elem
                }
            }
        }).result.then(()=> {
                this.checkState(elem);
            });
    }

    openReplicasForm(ser) {
        this._uiModal.open({
            animation: true,
            templateUrl: repTmp,
            controller: repCtrl,
            controllerAs: 'vm',
            resolve: {
                service: function () {
                    return ser;
                }
            }
        }).result.then(()=> {
                this.checkState(ser);
            });
    }

    editDetail() {
        this.content_edit = this.content;
        this.edition = true;
    }

    cancelEdit() {
        this.edition = false;
    }

    saveEdit() {
        this.edition = "loading";
        this._appSrv.update({id: this.id, content: this.content_edit}).then(()=> {
            this.content = this.content_edit;
            this.edition = false;
            this._notification.success('更新应用详情成功.');
        }).catch(data=> {
            this.edition = true;
            this._notification.error('更新应用详情失败.');
        })
    }
}
export default Detail